package com.sokal.easycare.modules.order.service;

import com.sokal.easycare.common.config.Global;
import com.sokal.easycare.common.persistence.Page;
import com.sokal.easycare.common.utils.NumberToCN;
import com.sokal.easycare.modules.order.entity.withdraw.UserWithdraw;
import com.sokal.easycare.modules.order.dao.withdraw.UserWithdrawDao;
import com.sokal.easycare.modules.order.entity.withdraw.WithdrawQuery;
import com.sokal.easycare.modules.payment.dao.TransactionRecordDao;
import com.sokal.easycare.modules.payment.dao.UserAccountDao;
import com.sokal.easycare.modules.payment.entity.TransactionRecord;
import com.sokal.easycare.modules.payment.entity.UserAccount;
import com.sokal.easycare.modules.sysparams.dao.SysParamsDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * 提现相关服务
 * Created by cwl on 2017/7/27.
 */
@Service
public class WithdrawService{

    @Autowired
    private UserWithdrawDao userWithdrawDao;

    @Autowired
    private TransactionRecordDao transactionRecordDao;

    @Autowired
    private UserAccountDao userAccountDao;

    @Autowired
    private SysParamsDao sysParamsDao;

    /**
     * 查询提现打印和处理操作信息
     * @param page
     * @param query
     * @return
     */
    public Page<UserWithdraw> listHandle(Page<UserWithdraw> page,WithdrawQuery query) {
        query.setPage(page);
        List<UserWithdraw> userWithdraws = userWithdrawDao.listByHandle(query);
        page.setList(userWithdraws);
        return page;
    }
    /**
     * 查询用户提现的所有流水信息
     * @param query
     * @return
     */
    public Page<UserWithdraw> listAllWithdraw(Page<UserWithdraw> page, WithdrawQuery query) throws Exception{
        query.setPage(page);
        List<UserWithdraw> userWithdraws;
        try {
            Float v = Float.parseFloat(sysParamsDao.getValueByName(Global.RATEPOUNDAGE));
            query.setPoundage(v);
            userWithdraws = userWithdrawDao.listAllWithdraw(query);

            Float minWithdraw = getMinWithdraw();//提现金额如果小于这个数，设置最低手续为minPoundage
            for (UserWithdraw userWithdraw : userWithdraws) {
                float money = Float.parseFloat(userWithdraw.getMoney());
                if (money < minWithdraw) {
                    float minPoundage = Float.parseFloat(sysParamsDao.getValueByName(Global.MINPOUNDAGE));
                    Float minFactMoney = money - minPoundage;
                    userWithdraw.setFactMoney(minFactMoney.toString());
                }
                //是否已打印
                UserWithdraw printUserWithdraw = userWithdrawDao.selectByPrimaryKey(userWithdraw.getId());
                if (null == printUserWithdraw) {
                    userWithdraw.setPrintTimes(0);
                } else {
                    userWithdraw.setPrintTimes(printUserWithdraw.getPrintTimes());
                }
            }


            page.setList(userWithdraws);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return new Page<>();
        }
        return page;
    }

    /**
     * 提现处理结果
     * @param transactionId 交易流水ID
     * @param status 处理结果 1，成功 -1 失败
     * @param userId 用户id
     * @param money 退加金额
     * @param nickname 处理人
     * @return
     */
    public Boolean handleWithdraw(String transactionId, String status, String userId,Double money,String nickname) {
        TransactionRecord transactionRecord = transactionRecordDao.get(transactionId);
        UserWithdraw userWithdraw = userWithdrawDao.selectByPrimaryKey(transactionId);
        try {
            //如果未打印，即提现表中无数据，则直接向提现表中插入一条数据
            if (userWithdraw == null) {
                //从流水表及相关表中查询出提现信息
                UserWithdraw userWithdrawByTransactionId = getUserWithdrawByTransactionId(transactionId);
                handlePrint(userWithdrawByTransactionId);
                userWithdraw = userWithdrawByTransactionId;
            }
            transactionRecord.setStatus("2");//修改流水状态为已处理
            transactionRecordDao.update(transactionRecord);

            userWithdraw.setHandleStatus("0");//已处理
            userWithdraw.setHandlePeople(nickname);//处理人

            if ("0".equals(status)) {
                userWithdraw.setStatus("0");//成功
                userWithdrawDao.updateByPrimaryKeySelective(userWithdraw);
            } else {//如果处理失败，退回提现金额到账户余额,handle_status为已处理 status为失败
                UserAccount userAccount = userAccountDao.get(userId);
                userAccount.setBalance(userAccount.getBalance() + money);//为用户添加余额
                userAccountDao.update(userAccount);
                userWithdraw.setStatus("-1");//失败
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 提现详情
     * @param transactionId 交易流水id
     *
     * @return
     */
    public UserWithdraw getUserWithdrawByTransactionId(String transactionId) throws Exception{
        UserWithdraw userWithdraw;
        try {
            Float poundage = Float.parseFloat(sysParamsDao.getValueByName(Global.RATEPOUNDAGE));
            userWithdraw = userWithdrawDao.getUserWithdrawByTransactionId(transactionId,poundage);
            float money = Float.parseFloat(userWithdraw.getMoney());
            Float factMoney;
            if (money < getMinWithdraw()) {
                float minPoundage = Float.parseFloat(sysParamsDao.getValueByName(Global.MINPOUNDAGE));
                factMoney = money - minPoundage;
                userWithdraw.setFactMoney(factMoney.toString());
            } else {
                factMoney = Float.parseFloat(userWithdraw.getFactMoney());
            }
            //转成中文大写
            BigDecimal numberOfMoney = new BigDecimal(factMoney);
            String s = NumberToCN.number2CNMontrayUnit(numberOfMoney);
            userWithdraw.setFactMoneyCN(s);
            //打印次数
            UserWithdraw printUserWithdraw = userWithdrawDao.selectByPrimaryKey(userWithdraw.getId());
            if (null == printUserWithdraw) {
                userWithdraw.setPrintTimes(0);
            } else {
                userWithdraw.setPrintTimes(printUserWithdraw.getPrintTimes());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return userWithdraw;
    }

    /**
     * 打印，向表中插入数据，如果存在，则打印次数加一
     * @param userWithdraw
     * @return
     */
    public Boolean handlePrint(UserWithdraw userWithdraw) throws Exception{
        UserWithdraw printUserWithdraw = userWithdrawDao.selectByPrimaryKey(userWithdraw.getId());

        try {
            if (null == printUserWithdraw) {//如果提现表中为空则插入一个数据
                userWithdraw.setTransaction(""+System.currentTimeMillis());
                userWithdraw.setPrintTimes(1);
                userWithdrawDao.insert(userWithdraw);
            } else {//否则打印次数加一
                userWithdraw.setPrintTimes(userWithdraw.getPrintTimes() + 1);
                userWithdrawDao.updateByPrimaryKey(userWithdraw);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 获取最低提现额度正常手续费
     * @return
     */
    private Float getMinWithdraw() {
        Float minPoundage = null;//最低手续费
        Float poundageRate = null;//手续费利率
        try {
            minPoundage = Float.parseFloat(sysParamsDao.getValueByName(Global.MINPOUNDAGE));
            poundageRate = Float.parseFloat(sysParamsDao.getValueByName(Global.RATEPOUNDAGE));
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return null;
        }
        return minPoundage / poundageRate;//提现金额如果小于这个数，设置最低手续为minPoundage
    }
}
